package core

import (
	"net"
	"time"
)

// PacketCapture IP数据包捕获器
type PacketCapture struct {
	conn   net.PacketConn
	buffer []byte
}

// NewPacketCapture 创建新的数据包捕获器
func NewPacketCapture() (*PacketCapture, error) {
	// 创建原始套接字
	conn, err := net.ListenPacket("ip4:ip", "0.0.0.0")
	if err != nil {
		return nil, err
	}

	return &PacketCapture{
		conn:   conn,
		buffer: make([]byte, 65535), // 最大IP包长度
	}, nil
}

// ReadPacket 读取一个IP数据包
func (pc *PacketCapture) ReadPacket() ([]byte, net.Addr, error) {
	n, addr, err := pc.conn.ReadFrom(pc.buffer)
	if err != nil {
		return nil, nil, err
	}

	// 复制数据到新的切片中返回
	data := make([]byte, n)
	copy(data, pc.buffer[:n])

	return data, addr, nil
}

// ReadPacketWithTimeout 带超时的读取数据包
func (pc *PacketCapture) ReadPacketWithTimeout(timeout time.Duration) ([]byte, net.Addr, error) {
	pc.conn.SetReadDeadline(time.Now().Add(timeout))
	defer pc.conn.SetReadDeadline(time.Time{})

	return pc.ReadPacket()
}

// Close 关闭捕获器
func (pc *PacketCapture) Close() error {
	return pc.conn.Close()
}
